package com.it.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it.config.ExecutorConfig;
import com.it.entity.User;
import com.it.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.*;

@Service
@Slf4j
public class RateLimitedDataFetcher {
    @Autowired
    private UserMapper userMapper;

    private static final int MAX_REQUESTS_PER_SECOND = 10;
    private Semaphore semaphore = new Semaphore(MAX_REQUESTS_PER_SECOND);
    private ExecutorService executorService = ExecutorConfig.getThreadPool();

    public Future<List<User>> fetchData(Integer id) {
        return executorService.submit((Callable<List<User>>) () -> {
            try {
                // 获取许可
                semaphore.acquire();
                // 执行网络请求，这里简化为一个延迟操作
                QueryWrapper qw = new QueryWrapper();
                //lt是小于，id小于5
                qw.lt("id", id);
                return userMapper.selectList(qw);
            } catch (InterruptedException e) {
                e.printStackTrace();
                return null;
            } finally {
                // 释放许可
                semaphore.release();
            }
        });
    }
}
